<template>
  <div class="upload-page">
    <h1>上传页面</h1>
    <form @submit.prevent="submitForm">
      <div class="form-group">
        <label for="title">标题:</label>
        <input
          type="text"
          id="title"
          v-model="title"
          placeholder="请输入标题"
          required
        />
      </div>

      <div class="form-group">
        <label for="content">主要内容:</label>
        <div id="editor"></div> <!-- Quill 编辑器的容器 -->
      </div>

      <div class="form-group">
        <label for="image">上传图片:</label>
        <input type="file" id="image" @change="handleFileUpload" accept="image/*" />
        <div v-if="imagePreview" class="image-preview">
          <img :src="imagePreview" alt="图片预览" />
        </div>
      </div>

      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';  // 引入 Quill 样式
const loginId = Number(localStorage.getItem('userId'));

// 表单数据
const title = ref('');
const content = ref('');
const imageFile = ref<File | null>(null);
const imagePreview = ref<string | null>(null);
const editor = ref<Quill | null>(null);

onMounted(() => {
  const quillEditor = new Quill('#editor', {
    theme: 'snow',
    placeholder: '请输入主要内容...'
  });

  editor.value = quillEditor;

  quillEditor.on('text-change', () => {
    content.value = quillEditor.root.innerHTML;
  });
});

// 图片上传处理
const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    imageFile.value = file;

    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      imagePreview.value = reader.result as string;
    };
  }
};

// 提交表单
const submitForm = async () => {
  if (!title.value || !content.value || content.value === '<p><br></p>') {
    alert('请填写所有必填字段');
    return;
  }

  const formData = new FormData();
  formData.append('userId', String(loginId))
  formData.append('title', title.value);
  formData.append('content', content.value);
  if (imageFile.value) {
    formData.append('image', imageFile.value);
  }

  try {
    const response = await axios.post('http://localhost:8080/information/uploadInformation', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (response.data.state) {
      alert("插入成功");
      title.value = '';
      content.value = '';
      if (editor.value) {
        editor.value.root.innerHTML = ''; // 清空 Quill 编辑器内容
      }
      imageFile.value = null;
      imagePreview.value = null;
    } else {
      alert(response.data.errMessage);
    }
  } catch (error) {
    alert("上传失败，请稍后再试");
  }
};
</script>

<style scoped>
.upload-page {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input[type='text'],
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
}

input[type='file'] {
  margin-top: 10px;
}

#editor {
  min-height: 200px;
  border: 1px solid #ccc;
  padding: 10px;
  background-color: white;
}

button {
  display: block;
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.image-preview {
  margin-top: 15px;
}

.image-preview img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
}
</style>
